package com.example.mall.controller;

import com.example.mall.common.api.CommonPage;
import com.example.mall.common.api.CommonResult;
import com.example.mall.dto.RoleDto;
import com.example.mall.mbg.model.Role;
import com.example.mall.mbg.model.Screen;
import com.example.mall.mbg.model.User;
import com.example.mall.service.RoleService;
import com.example.mall.service.ScreenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * RoleController
 * Created by on 2023/12/27.
 */
@Api(tags = "RoleController", description = "角色管理")
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private ScreenService screenService;

    private static final Logger LOGGER = LoggerFactory.getLogger(RoleController.class);

    @ApiOperation("画面：权限画面")
    @RequestMapping(value = "init",method = {RequestMethod.GET})
    public String init(Model model, HttpSession session) {
        List<RoleDto> roleDtos = new ArrayList<>();
        List<Role> roles = roleService.listAll();
        roles.forEach(role -> {
            RoleDto roleDto = new RoleDto(role);
            String[] screenids = role.getScreenids().split(",");
            List<Screen> screenList = new ArrayList<>();
            for (int i = 0; i < screenids.length; i++) {
                Screen screen = screenService.get(Integer.parseInt(screenids[i]));
                screenList.add(screen);
            }
            roleDto.setScreenList(screenList);
            roleDtos.add(roleDto);
        });
        model.addAttribute("roleDtos", roleDtos);
        Object user1 = session.getAttribute("user");
        if (user1 != null) {
            model.addAttribute("user", user1);
        }
        return "role-list";
    }

    @ApiOperation("画面：角色编辑")
    @RequestMapping(value = {"edit"},method = {RequestMethod.GET})
    public String edit(Model model, Integer roleid, HttpSession session) {
        Role role = roleService.get(roleid);
        RoleDto roleDto = new RoleDto(role);
        String[] screenids = role.getScreenids().split(",");
        List<Screen> screenList = new ArrayList<>();
        for (int i = 0; i < screenids.length; i++) {
            Screen screen = screenService.get(Integer.parseInt(screenids[i]));
            screenList.add(screen);
        }
        roleDto.setScreenList(screenList);
        roleDto.getScreenListStr();
        model.addAttribute("role", roleDto);
        Object user1 = session.getAttribute("user");
        if (user1 != null) {
            model.addAttribute("user", user1);
        }
        return "role-detail";
    }

    @ApiOperation("获取所有角色列表")
    @RequestMapping(value = "listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<RoleDto>> getRoleList() {
        List<RoleDto> roleDtos = new ArrayList<>();
        List<Role> roles = roleService.listAll();
        roles.forEach(role -> {
            RoleDto roleDto = new RoleDto(role);
            String[] screenids = role.getScreenids().split(",");
            List<Screen> screenList = new ArrayList<>();
            for (int i = 0; i < screenids.length; i++) {
                Screen screen = screenService.get(Integer.parseInt(screenids[i]));
                screenList.add(screen);
            }
            roleDto.setScreenList(screenList);
            roleDtos.add(roleDto);
        });
        return CommonResult.success(roleDtos);
    }

    @ApiOperation("添加角色")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult createRole(@RequestBody Role role) {
        CommonResult commonResult;
        int count = roleService.create(role);
        if (count == 1) {
            commonResult = CommonResult.success(role);
            LOGGER.debug("createRole success:{}", role);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("createRole failed:{}", role);
        }
        return commonResult;
    }

    @ApiOperation("更新指定id角色信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateRole(@PathVariable("id") Integer roleid, @RequestBody Role role, BindingResult bindingResult) {
        CommonResult commonResult;
        role.setUpdatetime(new Date());
        int count = roleService.update(roleid, role);
        if (count == 1) {
            commonResult = CommonResult.success(role);
            LOGGER.debug("updateRole success:{}", role);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("updateRole failed:{}", role);
        }
        return commonResult;
    }

    @ApiOperation("删除指定id的角色")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult deleteRole(@PathVariable("id") Integer roleid) {
        CommonResult commonResult;
        int count = roleService.delete(roleid);
        if (count == 1) {
            commonResult = CommonResult.success(null);
            LOGGER.debug("deleteRole success:id={}", roleid);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("deleteRole failed:id={}", roleid);
        }
        return commonResult;
    }

    @ApiOperation("分页查询角色列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<Role>> listRole(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {
        List<Role> roleList = roleService.list(pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(roleList));
    }

    @ApiOperation("获取指定id的角色详情")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Role> role(@PathVariable("id") Integer roleid) {
        return CommonResult.success(roleService.get(roleid));
    }
}
